<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { NButton, NCard, NSpace, NInput, NSelect, NSwitch, NTag, NModal, NForm, NFormItem, NPagination, NSpin, useMessage, useDialog } from 'naive-ui'
import { useRequest } from 'alova/client'
import { taskApi } from '@/service/api/bizhi'

const route = useRoute()

const message = useMessage()
const dialog = useDialog()

// 响应式数据
const loading = ref(false)
const tasks = ref<any[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
  pages: 0
})

// 搜索条件
const searchForm = reactive({
  keyword: '',
  is_completed: null,
  is_important: null,
  priority: null
})

// 模态框控制
const showModal = ref(false)
const modalType = ref<'create' | 'edit'>('create')
const currentTask = ref<any>(null)

// 表单数据
const formData = reactive({
  title: '',
  description: '',
  is_important: false,
  priority: 'medium'
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { max: 200, message: '标题不能超过200个字符', trigger: 'blur' }
  ]
}

// 优先级选项
const priorityOptions = [
  { label: '低', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高', value: 'high' }
]

// 状态选项
const statusOptions: any[] = [
  { label: '全部', value: null },
  { label: '未完成', value: false },
  { label: '已完成', value: true }
]

const importantOptions: any[] = [
  { label: '全部', value: null },
  { label: '普通', value: false },
  { label: '重要', value: true }
]

// 获取任务列表
const { send: fetchTasks } = useRequest(() => {
  // 过滤掉 null 值的参数
  const params: any = {
    page: pagination.page,
    limit: pagination.limit
  }

  // 只添加有效的搜索参数
  if (searchForm.keyword) params.keyword = searchForm.keyword
  if (searchForm.is_completed !== null) params.is_completed = searchForm.is_completed
  if (searchForm.is_important !== null) params.is_important = searchForm.is_important
  if (searchForm.priority !== null) params.priority = searchForm.priority

  return taskApi.getTaskList(params)
}, {
  immediate: false
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    const response: any = await fetchTasks()
    if (response.code === 200) {
      tasks.value = response.data.list
      Object.assign(pagination, response.data.pagination)
    } else {
      message.error(response.message || '获取任务列表失败')
    }
  } catch (error) {
    message.error('加载任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadTasks()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    is_completed: null,
    is_important: null,
    priority: null
  })
  pagination.page = 1
  loadTasks()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  loadTasks()
}

// 打开新增模态框
const handleCreate = () => {
  modalType.value = 'create'
  currentTask.value = null
  Object.assign(formData, {
    title: '',
    description: '',
    is_important: false,
    priority: 'medium'
  })
  showModal.value = true
}

// 打开编辑模态框
const handleEdit = (task: any) => {
  modalType.value = 'edit'
  currentTask.value = task
  Object.assign(formData, {
    title: task.title,
    description: task.description || '',
    is_important: task.is_important,
    priority: task.priority
  })
  showModal.value = true
}

// 表单引用
const formRef = ref()

// 保存任务
const { send: saveTask } = useRequest((data) => {
  if (modalType.value === 'create') {
    return taskApi.createTask(data)
  } else {
    return taskApi.updateTask(currentTask.value?.id, data)
  }
}, {
  immediate: false
})

const handleSave = async () => {
  try {
    // 验证表单
    await formRef.value?.validate()

    const response: any = await saveTask(formData)
    if (response.code === 200) {
      message.success(response.message || (modalType.value === 'create' ? '任务创建成功' : '任务更新成功'))
      showModal.value = false
      loadTasks()
    } else {
      message.error(response.message || (modalType.value === 'create' ? '任务创建失败' : '任务更新失败'))
    }
  } catch (error: any) {
    if (error?.length) {
      // 表单验证错误
      message.error('请检查表单输入')
    } else {
      message.error(modalType.value === 'create' ? '任务创建失败' : '任务更新失败')
    }
  }
}

// 切换完成状态
const { send: toggleComplete } = useRequest((id, is_completed) => 
  taskApi.updateTask(id, { is_completed }), {
  immediate: false
})

const handleToggleComplete = async (task: any) => {
  try {
    const response: any = await toggleComplete(task.id, !task.is_completed)
    if (response.code === 200) {
      message.success(response.message || (task.is_completed ? '任务标记为未完成' : '任务标记为已完成'))
      loadTasks()
    } else {
      message.error(response.message || '操作失败')
    }
  } catch (error) {
    message.error('操作失败')
  }
}

// 切换重要状态
const { send: toggleImportant } = useRequest((id, is_important) => 
  taskApi.updateTask(id, { is_important }), {
  immediate: false
})

const handleToggleImportant = async (task: any) => {
  try {
    const response: any = await toggleImportant(task.id, !task.is_important)
    if (response.code === 200) {
      message.success(response.message || (task.is_important ? '取消重要标记' : '标记为重要'))
      loadTasks()
    } else {
      message.error(response.message || '操作失败')
    }
  } catch (error) {
    message.error('操作失败')
  }
}

// 删除任务
const { send: deleteTask } = useRequest((id) => taskApi.deleteTask(id), {
  immediate: false
})

const handleDelete = (task: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除任务"${task.title}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        const response: any = await deleteTask(task.id)
        if (response.code === 200) {
          message.success(response.message || '任务删除成功')
          loadTasks()
        } else {
          message.error(response.message || '任务删除失败')
        }
      } catch (error) {
        message.error('任务删除失败')
      }
    }
  })
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  switch (priority) {
    case 'high': return 'error'
    case 'medium': return 'warning'
    case 'low': return 'info'
    default: return 'default'
  }
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'high': return '高'
    case 'medium': return '中'
    case 'low': return '低'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取任务详情
const { send: fetchTaskDetail } = useRequest((id: number) =>
  taskApi.getTaskDetail(id), {
  immediate: false
})

// 处理从通知点击进入的任务详情
const handleTaskFromNotification = async () => {
  const taskId = route.query.taskId
  if (taskId) {
    try {
      const response: any = await fetchTaskDetail(Number(taskId))
      if (response.code === 200) {
        // 打开编辑模态框显示任务详情
        handleEdit(response.data)
        // 清除URL参数
        window.history.replaceState({}, '', '/task')
      } else {
        message.error('任务不存在或已被删除')
      }
    } catch (error) {
      message.error('获取任务详情失败')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadTasks()
  // 检查是否有任务ID参数
  handleTaskFromNotification()
})

// 监听路由变化，处理新的任务ID参数
watch(() => route.query.taskId, (newTaskId) => {
  if (newTaskId) {
    handleTaskFromNotification()
  }
})
</script>

<template>
  <div class="task-management">
    <n-card title="任务管理">
      <template #header-extra>
        <n-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-park-outline-plus />
          </template>
          新增任务
        </n-button>
      </template>

      <!-- 搜索区域 -->
      <n-space vertical :size="16" class="mb-4">
        <n-space :size="16">
          <n-input
            v-model:value="searchForm.keyword"
            placeholder="搜索任务标题或描述"
            clearable
            style="width: 300px"
            @keyup.enter="handleSearch"
          />
          <n-select
            v-model:value="searchForm.is_completed"
            :options="statusOptions"
            placeholder="完成状态"
            clearable
            style="width: 120px"
          />
          <n-select
            v-model:value="searchForm.is_important"
            :options="importantOptions"
            placeholder="重要程度"
            clearable
            style="width: 120px"
          />
          <n-select
            v-model:value="searchForm.priority"
            :options="priorityOptions"
            placeholder="优先级"
            clearable
            style="width: 120px"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </n-space>

      <!-- 任务列表 -->
      <n-space vertical :size="12">
        <div v-if="loading" class="text-center py-8">
          <n-spin size="large" />
        </div>
        
        <div v-else-if="tasks.length === 0" class="text-center py-8 text-gray-500">
          暂无任务数据
        </div>
        
        <n-card
          v-else
          v-for="task in tasks"
          :key="task.id"
          size="small"
          :class="{ 'opacity-60': task.is_completed }"
        >
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-2">
                <n-switch
                  :value="task.is_completed"
                  size="small"
                  @update:value="() => handleToggleComplete(task)"
                />
                <h3 
                  class="text-lg font-medium"
                  :class="{ 'line-through': task.is_completed }"
                >
                  {{ task.title }}
                </h3>
                <n-tag
                  v-if="task.is_important"
                  type="error"
                  size="small"
                  round
                >
                  重要
                </n-tag>
                <n-tag
                  :type="getPriorityTagType(task.priority)"
                  size="small"
                >
                  {{ getPriorityText(task.priority) }}
                </n-tag>
              </div>
              
              <div v-if="task.description" class="text-gray-600 mb-2">
                <div v-html="task.description" class="prose prose-sm max-w-none"></div>
              </div>
              
              <div class="flex items-center gap-4 text-sm text-gray-500">
                <span>创建人: {{ task.creator?.nickname || task.creator?.username }}</span>
                <span>创建时间: {{ formatDate(task.created_at) }}</span>
                <span v-if="task.completed_at">完成时间: {{ formatDate(task.completed_at) }}</span>
              </div>
            </div>
            
            <div class="flex items-center gap-2 ml-4">
              <n-button
                size="small"
                :type="task.is_important ? 'error' : 'default'"
                @click="handleToggleImportant(task)"
              >
                <template #icon>
                  <icon-park-outline-star />
                </template>
                {{ task.is_important ? '取消重要' : '标记重要' }}
              </n-button>
              <n-button size="small" @click="handleEdit(task)">
                <template #icon>
                  <icon-park-outline-edit />
                </template>
              </n-button>
              <n-button size="small" type="error" @click="handleDelete(task)">
                <template #icon>
                  <icon-park-outline-delete />
                </template>
              </n-button>
            </div>
          </div>
        </n-card>
      </n-space>

      <!-- 分页 -->
      <div v-if="pagination.total > 0" class="flex justify-center mt-6">
        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pages"
          :page-size="pagination.limit"
          :item-count="pagination.total"
          show-size-picker
          show-quick-jumper
          @update:page="handlePageChange"
        />
      </div>
    </n-card>

    <!-- 新增/编辑模态框 -->
    <n-modal v-model:show="showModal" preset="dialog" style="width: 600px">
      <template #header>
        {{ modalType === 'create' ? '新增任务' : '编辑任务' }}
      </template>
      
      <n-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-placement="left"
        label-width="80px"
      >
        <n-form-item label="任务标题" path="title">
          <n-input v-model:value="formData.title" placeholder="请输入任务标题" />
        </n-form-item>
        
        <n-form-item label="任务描述" path="description">
          <MarkDownEditor v-model="formData.description" />
        </n-form-item>
        
        <n-form-item label="优先级" path="priority">
          <n-select v-model:value="formData.priority" :options="priorityOptions" />
        </n-form-item>

        <n-form-item label="重要任务" path="is_important">
          <n-switch v-model:value="formData.is_important" />
        </n-form-item>
      </n-form>
      
      <template #action>
        <n-space>
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" @click="handleSave">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<style scoped>
.task-management {
  padding: 20px;
}

.prose {
  max-width: none;
}

.prose h1, .prose h2, .prose h3, .prose h4, .prose h5, .prose h6 {
  margin-top: 0.5em;
  margin-bottom: 0.5em;
}

.prose p {
  margin-top: 0.25em;
  margin-bottom: 0.25em;
}

.prose ul, .prose ol {
  margin-top: 0.25em;
  margin-bottom: 0.25em;
}
</style>
